import type { NodeListItem } from '@/apis/model/node'
import type { SiteListItem } from '@/apis/model/site'
import { getApiNodeSimpleListDetailApi } from '@/apis/modules/node/node'
import {
  getApiSiteSimpleListApi,
  getApiSiteDetailApi
} from '@/apis/modules/site/site'
import { useSiteStore } from '@/stores/site'
export default function useTopSelect() {
  const route = useRoute()
  const router = useRouter()
  const selectList = ref<(NodeListItem | SiteListItem)[]>([])
  const options = ref<LabelValue[]>([])
  const paramsId = ref<string>('')

  const getSiteList = () => {
    getApiSiteSimpleListApi({}).then((res) => {
      selectList.value = res || []
      options.value = selectList.value
        .map((item: any) => ({ label: item.domain, value: item.id }))
        .filter(Boolean)
    })
  }
  const getNodeList = () => {
    getApiNodeSimpleListDetailApi({}).then((res) => {
      selectList.value = res || []
      selectList.value = res || []
      options.value = selectList.value
        .map((item: any) => ({ label: item.name, value: item.id }))
        .filter(Boolean)
    })
  }
  // //1:第一次获取数据 2:下拉加载更多
  const getList = (parentName: string) => {
    if (parentName === 'Site') {
      getSiteList()
    } else if (parentName === 'Node') {
      getNodeList()
    }
  }

  const handleSiteChange = (id: string) => {
    if (route.meta.parentName === 'Site') {
      getApiSiteDetailApi({ id: id }).then((res) => {
        useSiteStore().setSiteInfo(res)
        router.replace({ ...route, params: { id: id } })
      })
    } else {
      router.replace({ ...route, params: { id: id } })
    }
  }
  watch(
    () => route.meta.parentName,
    (newV, oldV) => {
      const newName = (newV as string) ?? ''
      const id = (route.params.id as string) ?? ''
      if (newV !== oldV && !!newName) {
        getList(newName)
      }
      if (id) {
        paramsId.value = id
      }
    },
    {
      immediate: true,
      deep: true
    }
  )

  return {
    paramsId,
    options,
    handleSiteChange
  }
}
